<template>
  <div>
    <div class="header-btn">
      <div>{{pageTitle}}</div>
      <div>
        <el-button type="primary" @click="CreatingConnection('ruleForm')" v-if="this.$route.query.operate !== 'DETAIL'" :loading="sureLoading">确认
        </el-button>
        <el-button type="info" plain @click="goBack">返回</el-button>
      </div>
    </div>
    <el-form label-width="120px" label-position="right" :model="ruleForm" :rules="rules" ref="ruleForm">
      <div class="wrap g-card" style="margin-bottom: 20px">
        <div class="title-header">链接设置</div>
        <template>
          <el-form-item label="链接地址" prop="materialUrl">
            <div v-if="this.$route.query.operate === 'DETAIL'">{{ ruleForm.materialUrl }}</div>
            <el-input v-else placeholder="请输入" v-model="ruleForm.materialUrl" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="链接标题" prop="title">
            <div v-if="this.$route.query.operate === 'DETAIL'">{{ ruleForm.title }}</div>
            <el-input v-else placeholder="请输入" v-model="ruleForm.title" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item :label="groupResolution" prop="categoryId">
            <div v-if="this.$route.query.operate === 'DETAIL'">{{ ruleForm.name }}</div>
            <el-select v-else v-model="ruleForm.categoryId" placeholder="请选择">
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="链接类型" prop="materialName">
            <el-radio-group v-model="ruleForm.materialName" v-if="this.$route.query.operate === 'DETAIL'">
              <el-radio disabled label="0">内部链接（雷达记录）</el-radio>
              <el-radio disabled label="1">永久跳转</el-radio>
            </el-radio-group>
            <el-radio-group v-model="ruleForm.materialName" v-else>
              <el-radio label="0">内部链接（雷达记录）</el-radio>
              <el-radio label="1">永久跳转</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="链接描述" prop="content">
            <div v-if="this.$route.query.operate === 'DETAIL'">{{ ruleForm.content }}</div>
            <el-input v-else v-model="ruleForm.content" type="textarea" placeholder="请输入" style="width: 400px"></el-input>
          </el-form-item>
        </template>
      </div>
      <div class="wrap g-card" style="margin-bottom: 20px">
        <div class="title-header">封面和摘要</div>
        <template>
          <el-form-item label="封面" prop="imgUrl" required>
            <el-upload v-if="this.$route.query.operate !== 'DETAIL'" class="avatar-uploader" action :before-upload="beforeAvatarUpload">
              <img v-if="ruleForm.imgUrl" style="width:230px;height:230px;border-radius: 10px;" :src="ruleForm.imgUrl" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <img v-if="this.$route.query.operate === 'DETAIL' && ruleForm.imgUrl" style="width:230px;height:230px;border-radius: 10px;" :src="ruleForm.imgUrl" />
          </el-form-item>
          <el-form-item v-if="this.$route.query.operate === 'DETAIL'" label="摘要">
            <div>{{ ruleForm.digest }}</div>
          </el-form-item>
          <el-form-item v-else label="摘要" prop="digest">
            <el-input v-model="ruleForm.digest" type="textarea" placeholder="选填，页面描述会在微信转发中显示，帮助客户快速了解内容" style="width: 400px"></el-input>
          </el-form-item>
        </template>
      </div>
      <div class="wrap g-card" style="margin-bottom: 20px">
        <div class="title-header">其他设置</div>
        <template>
          <el-form-item label="其他设置" v-if="this.$route.query.is_person == 1">
            <el-checkbox :disabled="this.$route.query.operate == 'DETAIL'" v-model="ruleForm.synchronization" @change="synchronization">同步到企业库
            </el-checkbox>
          </el-form-item>
          <el-form-item label="打标签" prop="groupTag">
            <tag-group v-model="ruleForm.weGroupTagVOS" :disabled="this.$route.query.operate === 'DETAIL'" />
          </el-form-item>
        </template>
      </div>
    </el-form>
  </div>
</template>

<script>
import { categoryList, creatinglinks, editTransfer, editTransferCorp, getLinklist, uploadFile } from '@/api/article/group'

export default {
  data() {
    return {
      pageTitle: '',
      titleOpt: {
        'ADD': '创建链接',
        'EDIT': '编辑链接',
        'DETAIL': '链接详情',
      },
      groupResolution: '个人分组',
      treeForm: {
        levelType: 1,
        mediaType: 11,
      },
      tags: '',
      tagVisible: false,
      domain: window.globalConfig.IMAGE_API,
      options: [],
      ruleForm: {
        groupTag: [],
        materialUrl: '',
        title: '',
        categoryId: '',
        content: '',
        coverUrl: '',
        imgUrl: '',
        digest: '',
        isSync: '',
        materialName: '0',
        companyCategoryId: '',
        weGroupTagVOS: [],
        id: this.$route.query.id,
        levelType: this.$route.query.levelType,
        mediaType: this.$route.query.mediaType,
      },
      rules: {
        materialUrl: [
          { required: true, message: '链接地址不能为空', trigger: 'blur' },
          {
            min: 10,
            max: 320,
            trigger: 'blur',
            message: '长度在 10 到 320 个字符',
          },
          {
            pattern: /((?:https?\:\/\/|http\.)(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)/i,
            message: '请输入以http://和https://开头的网址',
            trigger: 'blur',
          },
        ],
        title: [
          { required: true, message: '请输入链接标题', trigger: 'blur' },
          {
            min: 2,
            max: 32,
            message: '长度在 2 到 32 个字符',
            trigger: 'blur',
          },
        ],
        content: [
          {
            min: 5,
            max: 320,
            message: '长度在 5 到 320 个字符',
            trigger: 'blur',
          },
        ],
        categoryId: [
          { required: true, message: '请选择个人分组', trigger: 'blur' },
        ],
        materialName: [
          {
            required: true,
            message: '请至少选择一个活动性质',
            trigger: 'blur',
          },
        ],
        imgUrl: [{ required: true, message: '请上传封面', trigger: 'change' }],
        digest: [{ min: 5, max: 640, trigger: 'blur', message: '长度在 5 到 640 个字符' }],
      },
      sureLoading: false,
    }
  },
  created() {
    if (this.$route.query.levelType === 0) {
      this.groupResolution = '企业分组'
    }
    if (this.$route.query.operate == 'DETAIL' || this.$route.query.operate == 'EDIT') {
      this.getLinklist()
    }
    this.getCategory()
    this.pageTitle = this.titleOpt[this.$route.query.operate];
  },
  methods: {
    editTransfer() {
      this.ruleForm.mediaType = 11
      this.ruleForm = { ...this.ruleForm }
      this.sureLoading = false
      editTransfer(this.ruleForm)
        .then((res) => {
          if (res.code) {
            this.sureLoading = false
            this.$router.push({
              name: 'LinkManage',
              query: {
                // is_person: 3
                is_person: this.$route.query.is_person,
              },
            })
          } else {
            this.sureLoading = false
          }
        })
        .catch((err) => {
          this.sureLoading = false
        })
    },
    editTransferCorp() {
      this.ruleForm.mediaType = 11
      this.ruleForm = { ...this.ruleForm }
      this.sureLoading = false
      editTransferCorp(this.ruleForm)
        .then((res) => {
          if (res.code) {
            this.sureLoading = false
            this.$router.push({
              name: 'LinkManage',
              query: {
                // is_person: 3
                is_person: this.$route.query.is_person,
              },
            })
          } else {
            this.sureLoading = false
          }
        })
        .catch((err) => {
          this.sureLoading = false
        })
    },
    getLinklist() {
      const data = {
        id: this.$route.query.id,
        levelType: this.$route.query.levelType,
        mediaType: this.$route.query.mediaType,
      }
      getLinklist(data).then((res) => {
        if (res.code == 200 && res.rows.length > 0) {
          this.ruleForm = res.rows[0]
          this.$set(this.ruleForm, 'imgUrl',this.domain + this.ruleForm.coverUrl)
          this.ruleForm.weGroupTagVOS = this.ruleForm.tagVOS
          this.$set(this.ruleForm, 'digest', this.ruleForm.digest)
          if (this.ruleForm.isSync === '1') {
            this.$set(this.ruleForm, 'synchronization', true)
          } else if (this.ruleForm.isSync === '0') {
            this.$set(this.ruleForm, 'synchronization', false)
          }
        }
        console.log(this.ruleForm)
      }).catch((err) => {})
    },
    handleAddTag(value) {
      const arr1 = value.split(/[；;]/g)
      const arr2 = Array.from(new Set(arr1))
      if (arr1.length != arr2.length) {
        this.$message.error('有重复标签项')
        return
      } else {
        this.ruleForm.groupTag = arr1
        this.tagVisible = false
      }
      let tagList = []
      let arr = this.ruleForm.groupTag
      arr.forEach((item) => {
        item = String(item).replace(/^\s*|\s*$/g, '')
        if (tagList.indexOf(item) == -1 && item != '') {
          tagList.push(item)
        }
      })
      this.ruleForm.groupTag = tagList
    },
    handleCloseTag(tag) {
      this.ruleForm.groupTag.splice(this.ruleForm.groupTag.indexOf(tag), 1)
    },
    addTag() {
      this.tags = this.ruleForm.groupTag.join(';')
      this.tagVisible = true
    },
    CreatingConnection(formName) {
      // this.ruleForm.weGroupTagVOS = this.ruleForm.groupTag.join('；')
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.$route.query.id) {
                this.$route.query.levelType == '0'
                  ? this.editTransferCorp()
                  : this.editTransfer()
              } else {
                this.creatinglinks()
              }
            }
          })
        } else {
          this.$message.error('您还未录入完成，请核对后提交！')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    creatinglinks() {
      if (this.ruleForm.isSync === '0') {
        this.ruleForm.levelType = 0
      }
      if (this.ruleForm.isSync === '1') {
        this.ruleForm.levelType = 1
      }
      this.ruleForm.mediaType = 11
      this.ruleForm = { ...this.ruleForm }
      this.sureLoading = true
      creatinglinks(this.ruleForm)
        .then((res) => {
          if (res.code == 200) {
            this.sureLoading = false
            this.$router.push({
              name: 'LinkManage',
              query: { is_person: this.$route.query.is_person },
            })
          } else {
            this.sureLoading = false
          }
        })
        .catch(() => {
          this.sureLoading = false
        })
    },
    getCategory() {
      if (this.$route.query.levelType === 0) {
        this.treeForm.levelType = 0
      }
      categoryList(this.treeForm).then((res) => {
        if (res.code === 200) {
          this.options = res.data
        }
      })
    },
    // 封面上传
    beforeAvatarUpload(file) {
      const formData = new FormData()
      formData.append('file', file)
      uploadFile(formData)
        .then((res) => {
          if (res.code === 200) {
            this.ruleForm.coverUrl = res.data.url
            this.ruleForm.imgUrl = this.domain + res.data.url
          }
        })
        .catch((err) => {})
      return false
    },
    goBack() {
      // this.$router.back()
      if (+this.$route.query.is_person === 99) {
        this.$router.back(-1)
      } else {
        this.$router.push({
          name: 'LinkManage',
          query: { is_person: this.$route.query.is_person },
        })
      }
    },
    synchronization(i) {
      if (i) {
        this.ruleForm.isSync = '1'
      } else {
        this.ruleForm.isSync = '0'
      }
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/styles/base.scss';

.header-btn {
  @include headerBtn;
}

.wrap {
  @include titleWrap;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px solid #d9d9d9;
}
</style>
